<template>
  <div class="p-16px">
    <el-card>
      <div>
        <el-space :size="24">
          <div>设备编号：{{ deviceInfo.deviceCode }}</div>
          <div>设备名称：{{ deviceInfo.deviceName }}</div>
          <div>ICCID：{{ deviceInfo.deviceIccid }}</div>
          <div>设备密码：{{ deviceInfo.devicePassword }}</div>
          <el-button type="primary">修改</el-button>
        </el-space>
      </div>
      <el-space :size="24" class="mt-16px">
        <div>设备位置：{{ deviceInfo.deviceAddress }}</div>
        <div>硬件编号：{{ deviceInfo.deviceSnCode }}</div>
        <div>
          设备状态：
          <el-tag
            :type="deviceInfo.onlineStatus === 'offline' ? 'danger' : 'success'"
          >
            {{ deviceInfo.onlineStatusName }}
          </el-tag>
        </div>
        <el-button type="primary" plain>重启</el-button>
      </el-space>
    </el-card>
    <el-card class="mt-16px">
      <el-form :model="form" label-width="120px">
        <el-form-item label="轮播图">
          <el-select v-model="form.swiperAdId" style="width: 500px">
            <el-option label="请选择" value=""></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="待机广告">
          <el-select v-model="form.standbyAdId" style="width: 500px">
            <el-option label="请选择" value=""></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="广告音量">
          <el-input-number
            v-model="form.adVolume"
            :min="0"
            :max="15"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="提示音量">
          <el-input-number
            v-model="form.notifyVolume"
            :min="0"
            :max="7"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="静音时间段" style="width: 450px">
          <el-time-picker
            v-model="form.muteTime"
            is-range
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          ></el-time-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary">保存</el-button>
        </el-form-item>
        <el-form-item label="自定义指令">
          <el-space size="large">
            <el-input placeholder="请输入内容" clearable></el-input>
            <el-button type="primary">发送</el-button>
          </el-space>
        </el-form-item>
      </el-form>
    </el-card>
    <div class="device-con">
      <div class="mb-32px pl-64px">
        <el-button type="primary" @click="handleShowFullDialog('full')">
          一键补满
        </el-button>
      </div>
      <el-space :size="24">
        <el-space direction="vertical" :size="280">
          <div
            class="whitespace-nowrap"
            v-for="item in tableData"
            :key="item.roadRow"
          >
            第{{ item.roadRow }}层
          </div>
        </el-space>
        <el-space alignment="flex-start" direction="vertical" :size="24">
          <el-space :size="24" v-for="(item, index) in tableData" :key="index">
            <el-space
              direction="vertical"
              v-for="(child, childIndex) in item.roadUnitList"
              :key="childIndex"
            >
              <el-card
                class="w-200px h-280px flex flex-col items-center justify-center"
              >
                <p class="text-center mt-0">
                  ( {{ item.roadRow }} - {{ child.roadColumn }} )
                </p>
                <el-tooltip
                  effect="dark"
                  :content="child.goodsName"
                  placement="top"
                  v-if="child.goodsName"
                >
                  <div class="truncate w-140px mb-4px text-center">
                    {{ child.goodsName }}
                  </div>
                </el-tooltip>
                <div
                  class="truncate w-140px h-140px flex items-center justify-center mt-10px mb-14px text-center border border-dashed border-gray-300 rounded-md cursor-pointer hover:border-primary transition-all duration-300"
                  v-else
                  @click="handleShowGoodsDialog(child)"
                >
                  <el-icon class="text-24px">
                    <Plus />
                  </el-icon>
                </div>
                <el-image
                  v-if="child.thumbnailPicUrl"
                  :src="child.thumbnailPicUrl"
                  class="w-140px h-140px cursor-pointer"
                  fit="cover"
                  @click="handleShowGoodsStockDialog(child)"
                />
                <div class="text-center">
                  {{ child.goodsInventoryNum || 0 }}/{{
                    child.roadUnitCapacity
                  }}
                </div>
              </el-card>
            </el-space>
            <el-space direction="vertical" :size="16" class="mr-24px">
              <el-button
                class="w-100px"
                type="primary"
                @click="handleShowFullDialog('floor', item.roadRow)"
              >
                一键补满
              </el-button>
              <el-button
                class="w-100px"
                type="warning"
                @click="handleShowFullDialog('up', item.roadRow)"
              >
                一键上架
              </el-button>
            </el-space>
          </el-space>
        </el-space>
      </el-space>
    </div>
    <el-dialog title="上架商品" v-model="showGoodsDialog" style="width: 680px">
      <div>
        <el-space>
          <span>商品名称：</span>
          <el-input
            v-model="goodsTableParams.goodsName"
            placeholder="请输入商品名称"
          ></el-input>
          <el-button type="primary" @click="handleSearchGoods">搜索</el-button>
        </el-space>
      </div>
      <el-table :data="goodsTableData" v-loading="loading">
        <el-table-column label="商品图片" prop="thumbnailPicUrl" width="120px">
          <template #default="{ row }">
            <el-image
              :src="row.thumbnailPicUrl"
              class="w-80px h-80px"
              fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column label="商品名称" prop="goodsName"></el-table-column>
        <el-table-column label="操作" prop="operation" width="90px">
          <template #default="{ row }">
            <el-button type="primary" @click="handleSelectGoods(row)">
              选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="goodsTableParams.current"
        v-model:page-size="goodsTableParams.size"
        :small="small"
      />
    </el-dialog>
    <el-dialog
      title="商品补货"
      v-model="showGoodsStockDialog"
      style="width: 680px"
    >
      <el-form :model="goodsForm" label-width="100px">
        <el-form-item label="商品名称">
          <span>{{ goodsForm.goodsName }}</span>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-image
            :src="goodsForm.thumbnailPicUrl"
            class="w-150px h-150px"
            fit="cover"
          />
        </el-form-item>
        <el-form-item label="数量">
          <el-input-number
            v-model="goodsForm.editInventoryNum"
            :min="-100"
            :max="100"
            :step="1"
          />
        </el-form-item>
        <el-form-item label="临期警告">
          <el-input-number
            v-model="goodsForm.nearExpireDays"
            :min="0"
            :max="30"
            :step="1"
          >
            <template #suffix>天</template>
          </el-input-number>
          <el-tooltip
            effect="dark"
            content="临期告警0即为不告警"
            placement="top"
          >
            <el-icon class="text-24px ml-8px"><InfoFilled /></el-icon>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="过期天数">
          <el-input-number
            v-model="goodsForm.realExpireDays"
            :min="0"
            :max="30"
            :step="1"
          >
            <template #suffix>天</template>
          </el-input-number>
          <el-tooltip
            effect="dark"
            content="过期天数0即为不过期"
            placement="top"
          >
            <el-icon class="text-24px ml-8px"><InfoFilled /></el-icon>
          </el-tooltip>
        </el-form-item>
        <el-form-item>
          <el-space size="large">
            <el-button
              type="danger"
              @click="handleGoodsDownShelf"
              :loading="submitLoading"
            >
              下架
            </el-button>
            <el-button
              type="primary"
              @click="handleGoodsStock"
              :loading="submitLoading"
            >
              确认补货
            </el-button>
            <el-button @click="showGoodsStockDialog = false">取消</el-button>
          </el-space>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="一键补满" v-model="showFullDialog" style="width: 680px">
      <div>
        <div>
          <el-space>
            <span>临期告警：</span>
            <el-input-number
              v-model="fullForm.nearExpireDays"
              :min="0"
              :max="100"
              :step="1"
            ></el-input-number>
            <el-tooltip
              effect="dark"
              content="临期告警0即为不告警"
              placement="top"
            >
              <el-icon class="text-24px ml-8px"><InfoFilled /></el-icon>
            </el-tooltip>
          </el-space>
        </div>
        <div class="mt-16px">
          <el-space>
            <span>过期天数：</span>
            <el-input-number
              v-model="fullForm.realExpireDays"
              :min="0"
              :max="100"
              :step="1"
            ></el-input-number>
            <el-tooltip
              effect="dark"
              content="过期天数0即为不过期"
              placement="top"
            >
              <el-icon class="text-24px ml-8px"><InfoFilled /></el-icon>
            </el-tooltip>
          </el-space>
        </div>
        <div class="mt-24px pl-80px">
          <el-space size="large">
            <el-button
              type="primary"
              @click="handleFull"
              :loading="submitLoading"
            >
              确认
            </el-button>
            <el-button @click="showFullDialog = false">取消</el-button>
          </el-space>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useCommonStoreHook } from "@/store/modules/common";
import { useRoute } from "vue-router";

const commonStore = useCommonStoreHook();
const route = useRoute();
const tableData = ref([]);
const deviceInfo = ref({});
const showFullDialog = ref(false);
const showGoodsDialog = ref(false);
const showGoodsStockDialog = ref(false);
const loading = ref(false);
const submitLoading = ref(false);
const goodsForm = ref({});
const goodsTableData = ref([]);
const goodsTableParams = ref({
  current: 1,
  size: 10,
  goodsName: "",
});
const form = ref({
  swiperAdId: "",
  standbyAdId: "",
  adVolume: 0,
  notifyVolume: 0,
  muteTime: [],
});
const fullForm = ref({
  nearExpireDays: 0,
  realExpireDays: 0,
});
const handleFull = () => {
  submitLoading.value = true;
  commonStore
    .quickFullRoadUnitGoods(fullForm.value)
    .then(() => {
      ElMessage.success("一键补满成功");
      showFullDialog.value = false;
      fetchDeviceInfoDetailByCode();
    })
    .finally(() => {
      submitLoading.value = false;
    });
};
const handleShowFullDialog = (type, roadRow) => {
  if (type === "up") {
    showGoodsDialog.value = true;
    handleSearchGoods();
    goodsForm.value = {
      roadRow,
      editInventoryNum: 0,
      nearExpireDays: null,
      realExpireDays: null,
      deviceCode: route.query.deviceCode,
    };
  } else {
    showFullDialog.value = true;
    fullForm.value = {
      type,
      roadRow,
      nearExpireDays: 0,
      realExpireDays: 0,
      deviceCode: route.query.deviceCode,
    };
  }
};
const handleSearchGoods = () => {
  loading.value = true;
  commonStore
    .queryGoodsPage(goodsTableParams.value)
    .then((res) => {
      goodsTableData.value = res.records;
    })
    .finally(() => {
      loading.value = false;
    });
};

const fetchDeviceInfoDetailByCode = () => {
  loading.value = true;
  commonStore
    .getDeviceInfoDetailByCode({ deviceCode: route.query.deviceCode })
    .then((res) => {
      deviceInfo.value = res;
      tableData.value = res.roadUnitRowList;
    })
    .finally(() => {
      loading.value = false;
    });
};
const handleSelectGoods = (row) => {
  goodsForm.value.goodsId = row.id;
  loading.value = true;
  const fn = goodsForm.value.roadRow
    ? "quickUpShelfRoadUnitGoods"
    : "operateDeviceRoadUnitGoods";
  commonStore[fn](goodsForm.value)
    .then(() => {
      showGoodsDialog.value = false;
      fetchDeviceInfoDetailByCode();
    })
    .finally(() => {
      loading.value = false;
    });
};
const handleShowGoodsDialog = (row) => {
  showGoodsDialog.value = true;
  goodsForm.value = {
    roadUnitCode: row.roadUnitCode,
    deviceCode: row.deviceCode,
    operateType: "up_shelf",
    editInventoryNum: 0,
    nearExpireDays: null,
    realExpireDays: null,
    goodsId: "",
  };
  handleSearchGoods();
};
const handleGoodsStock = () => {
  if (goodsForm.value.editInventoryNum === 0) {
    ElMessage.warning("请输入数量");
    return;
  }
  goodsForm.value.operateType =
    goodsForm.value.editInventoryNum > 0 ? "plus_num" : "reduce_num";
  goodsForm.value.editInventoryNum = Math.abs(goodsForm.value.editInventoryNum);
  submitLoading.value = true;
  commonStore
    .operateDeviceRoadUnitGoods(goodsForm.value)
    .then(() => {
      showGoodsStockDialog.value = false;
      fetchDeviceInfoDetailByCode();
    })
    .finally(() => {
      submitLoading.value = false;
    });
};
const handleGoodsDownShelf = () => {
  submitLoading.value = true;
  goodsForm.value.operateType = "down_shelf";
  commonStore
    .operateDeviceRoadUnitGoods(goodsForm.value)
    .then(() => {
      ElMessage.success("下架成功");
      showGoodsStockDialog.value = false;
      fetchDeviceInfoDetailByCode();
    })
    .finally(() => {
      submitLoading.value = false;
    });
};
const handleShowGoodsStockDialog = (row) => {
  showGoodsStockDialog.value = true;
  goodsForm.value = {
    roadUnitCode: row.roadUnitCode,
    deviceCode: row.deviceCode,
    operateType: "plus_num",
    editInventoryNum: row.goodsInventoryNum,
    nearExpireDays: row.nearExpireDays || 0,
    realExpireDays: row.realExpireDays || 0,
    goodsId: row.goodsId,
    thumbnailPicUrl: row.thumbnailPicUrl,
    goodsName: row.goodsName,
  };
};

onMounted(() => {
  fetchDeviceInfoDetailByCode();
});
</script>

<style lang="scss" scoped>
.device-con {
  padding: 24px 16px;
  background-color: var(--el-bg-color-page);
}
</style>
